package org.example.StudentManagementSystem.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.example.StudentManagementSystem.mapper.UserMapper;
import org.example.StudentManagementSystem.entity.User;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.List;

@Component
public class TokenUtils {
    private static UserMapper staticUserMapper;

    @Resource
    UserMapper userMapper;

    @PostConstruct
    public void setUserService() {
        staticUserMapper = userMapper;
    }

    /**
     * 生成token
     */
    public static String genToken(String userId, String sign) {
        //2小时后过期
        ZonedDateTime zonedDateTime = LocalDateTime.now().plusHours(2).atZone(ZoneId.systemDefault());
        Instant expiresAt = zonedDateTime.toInstant();
        return JWT.create().withAudience(userId)
                .withExpiresAt(expiresAt)
                .sign(Algorithm.HMAC256(sign));
    }

    /**
     * 获取当前登录的用户信息
     */
    public static User getCurrentUser() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("Token");
            if (token == null) {
                token = request.getParameter("Token");
            }
            if (token != null) {
                List<String> audience = JWT.decode(token).getAudience();
                if (audience != null && !audience.isEmpty()) {
                    String userId = audience.get(0); // 使用 get(0) 替代 getFirst()
                    return staticUserMapper.selectById(Integer.valueOf(userId));
                }
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }
}